
// 获取项目访问绝对路径
function getRealPath() {
	var curWwwPath = window.document.location.href;
	// 获取主机地址之后的目录，如： myproj/view/my.jsp
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	// 获取主机地址，如： http://localhost:8083
	var localhostPaht = curWwwPath.substring(0, pos);
	// 获取带"/"的项目名，如：/myproj
	var projectName = pathName
			.substring(0, pathName.substr(1).indexOf('/') + 1);
	// 得到了 http://localhost:8083/myproj
	var realPath = localhostPaht;
	return realPath;
}

// 判断是否为null
function panIsNull(variable1) {
	if (variable1 != null && variable1 != undefined && variable1 != '') {
		return false;
	}
	return true;
}


//ajax查询url
var searchListUrl='';

//to添加url
var toAddUrl='';

//to编辑url
var toEditUrl='';

//删除url
var delUrl='';

//链接初始化
function initUrl(surl, taddurl, toediturl, delurl) {
	searchListUrl = surl;
	toAddUrl = taddurl;
	toEditUrl = toediturl;
	delUrl = delurl;
}

// 查询
function baseSearchQuery(pageindex) {
    idArray = [];
	if (pageindex == 'Refresh') {
		pageindex = $("#currentPage").val();
	}
	if(panIsNull(pageindex)){
		pageindex = 1;
	}
	var loadi = layer.load();
	var datajson = $("#searchForm").serialize();
	var searchurl = searchListUrl;
	if(searchurl.indexOf('?')!=-1){
        searchurl = searchurl + "&current=" + pageindex;
	}else{
        searchurl = searchurl + "?current=" + pageindex;
	}
	$.ajax({
		type : "POST",
		url : searchurl,
		data : datajson,
		dataType : "text",
		async : true,
		success : function(data) {
            layer.close(loadi);
			$("#pageList").html(data);
		}
	});
}

// 查询
function baseSearchQueryLayer(pageindex,size) {
	idArray = [];
    if (pageindex == 'Refresh') {
        pageindex = $("#currentPage").val();
    }
    if(panIsNull(pageindex)){
        pageindex = 1;
    }
    if (size == 'Refresh') {
        size = $("#sizePage").val();
    }
    if(panIsNull(size)){
        size = 20;
    }
    var loadi = layer.load();
    var datajson = $("#searchForm").serialize();
    var searchurl = searchListUrl;
    if(searchurl.indexOf('?')!=-1){
        searchurl = searchurl + "&current=" + pageindex;
    }else{
        searchurl = searchurl + "?current=" + pageindex;
    }
    if(searchurl.indexOf('?')!=-1){
        searchurl = searchurl + "&size=" + size;
	}else{
        searchurl = searchurl + "&size=" + size;
	}
    $.ajax({
        type : "POST",
        url : searchurl,
        data : datajson,
        dataType : "text",
        async : true,
        success : function(data) {
            layer.close(loadi);
            $("#pageList").html(data);
        }
    });
}

// To add 标题>>长>>宽>>是否全屏
function toBaseAdd(title, width, height , layerFull) {
	var baseAdd = layer.open({
		type : 2,
		title : title,
		shadeClose : true,
		shade : false,
		maxmin : true, // 开启最大化最小化按钮
		area : [ width + 'px', height + 'px' ],
		content : toAddUrl
	});
	if(layerFull){
		layer.full(baseAdd);
	}
}

// To add 标题>>长>>宽>>是否全屏
function toBaseLayer(title, width, height , layerFull, urls) {
    var baseAdd = layer.open({
        type : 2,
        title : title,
        shadeClose : true,
        shade : false,
        maxmin : false, // 开启最大化最小化按钮
        area : [ width + 'px', height + 'px' ],
        content : urls
    });
    if(layerFull){
        layer.full(baseAdd);
    }
}

// 添加
function baseAddNotClose(url) {
	$("#submitForm").trigger("validate");
	instance = $("#submitForm").data("validator");
	if (instance.isFormValid()) {
		var loadi = layer.load();
		var datajson = $("#submitForm").serialize();
		$.ajax({
			type : "POST",
			url : url,
			data : datajson,
			dataType : "json",
			success : function(data) {
				layer.close(loadi);
				if (data.status == 'SUCCESS') {
					window.baseBottomMsgOpen('添加成功');
				} else {
					layer.alert(data.msg);
				}
			}
		});
	}
}

var baseAddShowMsg = '添加成功';

// 添加
function baseAdd(url) {
    var index = parent.layer.getFrameIndex(window.name);
    $("#submitForm").trigger("validate");
    instance = $("#submitForm").data("validator");
    if (instance.isFormValid()) {
        var loadi = layer.load();
        var datajson = $("#submitForm").serialize();
        $.ajax({
            type : "POST",
            url : url,
            data : datajson,
            dataType : "json",
            success : function(data) {
                layer.close(loadi);
                if (data.status == 'SUCCESS') {
                    window.parent.baseSearchQueryLayer('Refresh','Refresh');
					if(!panIsNull(data.msg)){
						window.parent.baseBottomMsgOpen(data.msg);
					}else{
						window.parent.baseBottomMsgOpen(baseAddShowMsg);
					}
                    window.parent.layer.close(index);
                } else {
                    layer.alert(data.msg);
                }
            }
        });
    }
}


// 添加
function baseNotValid(url) {
    var index = parent.layer.getFrameIndex(window.name);
	var loadi = layer.load();
	var datajson = $("#submitForm").serialize();
	$.ajax({
		type : "POST",
		url : url,
		data : datajson,
		dataType : "json",
		success : function(data) {
			layer.close(loadi);
			if (data.status == 'SUCCESS') {
				window.parent.baseSearchQueryLayer('Refresh','Refresh');
				window.parent.baseBottomMsgOpen('操作成功');
				window.parent.layer.close(index);
			} else {
				layer.alert(data.msg);
			}
		}
	});
}

var addRspSuccessStr = '操作成功';

//添加
function baseAddSetRsp(url) {
	var index = parent.layer.getFrameIndex(window.name);
	$("#submitForm").trigger("validate");
	instance = $("#submitForm").data("validator");
	if (instance.isFormValid()) {
		var loadi = layer.load();
		var datajson = $("#submitForm").serialize();
		$.ajax({
			type : "POST",
			url : url,
			data : datajson,
			dataType : "json",
			success : function(data) {
				layer.close(loadi);
				if (data.status == 'SUCCESS') {
					window.parent.baseSearchQueryLayer('Refresh','Refresh');
					window.parent.baseBottomMsgOpen(addRspSuccessStr);
					window.parent.layer.close(index);
				} else {
					layer.alert(data.msg);
				}
			}
		});
	}
}

// TO 修改
function toBaseEdit(title, width, height,layerFull) {
	var allSum = $("input[name='idArray']:checked");
	if (parseInt(allSum.length) != 1) {
		layer.alert('请选择一条数据', {
			icon : 2
		});
		return;
	}
	var id = $(allSum[0]).val();
    var toEditUrlNew = toEditUrl;
    if(toEditUrlNew.indexOf('?')!=-1){
        toEditUrlNew = toEditUrlNew + '&id=' + id;
    }else{
        toEditUrlNew = toEditUrlNew + '?id=' + id;
    }
	var baseEdit = layer.open({
		type : 2,
		title : title,
		shadeClose : true,
		shade : false,
		maxmin : true, // 开启最大化最小化按钮
		area : [ width + 'px', height + 'px' ],
		content : toEditUrlNew
	});
	if(layerFull){
		layer.full(baseEdit);
	}
}

// TO 修改
function toBaseSelEdit(obj,title, width, height,layerFull) {
	var id = $(obj).attr("data-id");
    var toEditUrlNew = toEditUrl;
    if(toEditUrlNew.indexOf('?')!=-1){
        toEditUrlNew = toEditUrlNew + '&id=' + id;
    }else{
        toEditUrlNew = toEditUrlNew + '?id=' + id;
    }
    var baseEdit = layer.open({
        type : 2,
        title : title,
        shadeClose : true,
        shade : false,
        maxmin : true, // 开启最大化最小化按钮
        area : [ width + 'px', height + 'px' ],
        content : toEditUrlNew
    });
    if(layerFull){
        layer.full(baseEdit);
    }
}


// TO 导入
function toBaseImp(title, impUrl, width, height) {
	layer.open({
		type : 2,
		title : title,
		shadeClose : true,
		shade : false,
		maxmin : true, // 开启最大化最小化按钮
		area : [ width + 'px', height + 'px' ],
		content : impUrl
	});

}

var baseEditShowMsg = '修改成功';

// 修改
function baseEdit(url) {
	// 循环取值
	var index = parent.layer.getFrameIndex(window.name);
	$("#submitForm").trigger("validate");
	instance = $("#submitForm").data("validator");
	if (instance.isFormValid()) {
		var loadi = layer.load();
		var datajson = $("#submitForm").serialize();
		$.ajax({
			type : "POST",
			url : url,
			data : datajson,
			dataType : "json",
			success : function(data) {
				layer.close(loadi);
				if (data.status == 'SUCCESS') {
					window.parent.baseSearchQueryLayer('Refresh','Refresh');
					window.parent.baseBottomMsgOpen(baseEditShowMsg);
					window.parent.layer.close(index);
				} else {
					layer.alert(data.msg);
				}
			}
		});
	}
}

// 修改
function basePost(url) {
    // 循环取值
	var loadi = layer.load();
	$.ajax({
		type : "POST",
		url : url,
		dataType : "json",
		success : function(data) {
			layer.close(loadi);
			if (data.status == 'SUCCESS') {
                baseSearchQueryLayer('Refresh','Refresh');
				baseBottomMsgOpen('操作成功');
			} else {
				layer.alert(data.msg);
			}
		}
	});
}


function eachBox(obj) {
	var array = '';
	$.each(obj, function(n, item) {
		array += $(item).val() + ',';
	});
	array = array.substring(0, array.length - 1);
	return array;
}

var checkboxed = false;// 默认不选中

// 列表选中
function getCheckBox(obj) {
	var allSum = $("input[name='idArray']");
	if (checkboxed == true) {
		checkboxed = false;
		for (var i = 0; i < allSum.length; i++) {
			$(allSum[i]).attr("checked", false);
		}
	} else {
		checkboxed = true;
		for (var i = 0; i < allSum.length; i++) {
			$(allSum[i]).attr("checked", true);
		}
	}
}

// 删除
function baseDel() {
	// 判断是否选中
	var allSum = $("input[name='idArray']:checked");
	if (parseInt(allSum.length) == 0) {
		layer.alert('请选择你要删除的数据!', {
			icon : 2
		});
		return;
	}
	layer.confirm("您确定要删除" + parseInt(allSum.length) + "条数据吗?", {
		btn : [ '确定', '取消' ], // 按钮
		shade : false
	// 显示遮罩
	}, function() {
		var loadi = layer.load();
		$.ajax({
			type : "POST",
			url : delUrl,
			data : {
				"id" : eachBox(allSum)
			},
			dataType : "json",
			async : true,
			success : function(data) {
				layer.close(loadi);
				if (data.status == 'SUCCESS') {
					baseSearchQuery('Refresh');
					baseBottomMsgOpen('删除成功');
				} else {
					layer.alert(data.msg);
				}
			}
		});
	}, function() {
		// 取消
	});
}

// 删除
function baseSelDel(obj) {
    var id = $(obj).attr("data-id");
    layer.confirm("您确定要删除这条数据吗?", {
        btn : [ '确定', '取消' ], // 按钮
        shade : false
        // 显示遮罩
    }, function() {
        var loadi = layer.load();
        $.ajax({
            type : "POST",
            url : delUrl,
            data : {
                "id" : id
            },
            dataType : "json",
            async : true,
            success : function(data) {
                layer.close(loadi);
                if (data.status == 'SUCCESS') {
                    baseSearchQueryLayer('Refresh','Refresh');
                    baseBottomMsgOpen('删除成功');
                } else {
                    layer.alert(data.msg);
                }
            }
        });
    }, function() {
        // 取消
    });
}

// 右下角弹出信息 2秒关闭
function baseBottomMsgOpen(msg) {
	layer.open({
		offset : 'cc', // 右下角弹出
		shift : 2,
		time : 3000,
		icon : 1,
		skin : 'layui-layer-demo', // 样式类名
		content : msg,
		shadeClose : true, // 开启遮罩关闭
		shade : false,
		area : [ '260px', '140px' ],
		btn : []
	});
}

// 判断是不是整数
function isInteger(obj) {
	return typeof obj === 'number' && obj%1 === 0
}

function layerTips(obj){
    layer.alert($(obj).attr("datas"));
}

function layerTipsMsg(msg){
    layer.alert(msg);
}

// 模块点击
function modularTitleOnClick(obj){
	var displays = $(obj).parent().next().css("display");
	if(displays == 'block'){
        $(obj).parent().next().css("display","none");
        $(obj).html("<i class='layui-icon'>&#xe61a;</i>展开");
	}else{
        $(obj).parent().next().css("display","block");
        $(obj).html("<i class='layui-icon'>&#xe619;</i>收缩");
	}

}


var idArray = [];
function selCheckbox(obj){
    if(!obj.checked){
        if(obj.type == 'one'){
            idArray = $.grep(idArray, function(value) {
                return value != obj.data.id;
            });
        }
        if(obj.type == 'all'){
            idArray = [];
        }
    }
    if(obj.checked){
        if(obj.type == 'all'){
            idArray = [];
            var tabletr = $("#tableList").find('tr');
            $.each(tabletr, function(n, item) {
                var values = $(item).attr('data-itemId');
                if(panIsNull(values)){
                    return true;
                }
                idArray.push(values);
            });
        }
        if(obj.type == 'one'){
            idArray.push(obj.data.id);
        }
    }
}
var paramArrayBase = [];
function selCheckboxForParamBase(obj, param){
    if(!obj.checked){
        if(obj.type == 'one'){
            paramArrayBase = $.grep(paramArrayBase, function(value) {
                return value != obj.data.id;
            });
        }
        if(obj.type == 'all'){
            paramArrayBase = [];
        }
    }
    if(obj.checked){
        if(obj.type == 'all'){
            paramArrayBase = [];
            var tabletr = $("#tableList").find('tr');
            $.each(tabletr, function(n, item) {
                var values = $(item).attr(param);
                if(panIsNull(values)){
                    return true;
                }
                paramArrayBase.push(values);
            });
        }
        if(obj.type == 'one'){
            paramArrayBase.push(obj.data.id);
        }
    }
}

function getCheckValues(){
    return idArray.join(',');
}

/*
 * MAP对象，实现MAP功能
 *
 * 接口：
 * size()     获取MAP元素个数
 * isEmpty()    判断MAP是否为空
 * clear()     删除MAP所有元素
 * put(key, value)   向MAP中增加元素（key, value)
 * remove(key)    删除指定KEY的元素，成功返回True，失败返回False
 * get(key)    获取指定KEY的元素值VALUE，失败返回NULL
 * element(index)   获取指定索引的元素（使用element.key，element.value获取KEY和VALUE），失败返回NULL
 * containsKey(key)  判断MAP中是否含有指定KEY的元素
 * containsValue(value) 判断MAP中是否含有指定VALUE的元素
 * values()    获取MAP中所有VALUE的数组（ARRAY）
 * keys()     获取MAP中所有KEY的数组（ARRAY）
 *
 * 例子：
 * var map = new Map();
 *
 * map.put("key", "value");
 * var val = map.get("key")
 * ……
 *
 */
function Map() {
    this.elements = new Array();

    //获取MAP元素个数
    this.size = function() {
        return this.elements.length;
    }

    //判断MAP是否为空
    this.isEmpty = function() {
        return(this.elements.length < 1);
    }

    //删除MAP所有元素
    this.clear = function() {
        this.elements = new Array();
    }

    //向MAP中增加元素（key, value)
    this.put = function(_key, _value) {
        this.elements.push( {
            key : _key,
            value : _value
        });
    }

    //删除指定KEY的元素，成功返回True，失败返回False
    this.remove = function(_key) {
        var bln = false;
        try{
            for(i = 0; i < this.elements.length; i++) {
                if(this.elements[i].key == _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch(e) {
            bln = false;
        }
        return bln;
    }

    //获取指定KEY的元素值VALUE，失败返回NULL
    this.get = function(_key) {
        try{
            for(i = 0; i < this.elements.length; i++) {
                if(this.elements[i].key == _key) {
                    return this.elements[i].value;
                }
            }
        } catch(e) {
            return null;
        }
    }

    //获取指定索引的元素（使用element.key，element.value获取KEY和VALUE），失败返回NULL
    this.element = function(_index) {
        if(_index < 0 || _index >= this.elements.length) {
            return null;
        }
        return this.elements[_index];
    }

    //判断MAP中是否含有指定KEY的元素
    this.containsKey = function(_key) {
        varbln = false;
        try{
            for(i = 0; i < this.elements.length; i++) {
                if(this.elements[i].key == _key) {
                    bln = true;
                }
            }
        } catch(e) {
            bln = false;
        }
        return bln;
    }

    //判断MAP中是否含有指定VALUE的元素
    this.containsValue = function(_value) {
        var bln = false;
        try{
            for(i = 0; i < this.elements.length; i++) {
                if(this.elements[i].value == _value) {
                    bln = true;
                }
            }
        } catch(e) {
            bln = false;
        }
        return bln;
    }

    //获取MAP中所有VALUE的数组（ARRAY）
    this.values = function() {
        var arr = new Array();
        for(i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].value);
        }
        return arr;
    }

    //获取MAP中所有KEY的数组（ARRAY）
    this.keys = function() {
        var arr = new Array();
        for(i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].key);
        }
        return arr;
    }
}

//打印所选区域内的内容
function preview(fun)
{
    bdhtml=window.document.body.innerHTML;
    sprnstr="<!--startprint-->";
    eprnstr="<!--endprint-->";
    prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+17);
    prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
        // prnhtml.replace('<!--imgHidden-->', '<img src="' + getRealPath() + '/images/300.jpg" alt="300.jpg" width="290" height="72" style="width: 290px; height: 72px;"/>');
    window.document.body.innerHTML=prnhtml;
    if (!panIsNull(fun)) {
        fun();
    }
    window.print();
    // window.location.reload();
}

function printDiv2Img(fileName) {
    var w = $("#printDiv").width();
    var h = $("#printDiv").height();

    var canvas = document.createElement("canvas");
    canvas.width = w*2;
    canvas.height = h*2;
    canvas.style.width = w + "px";
    canvas.style.height = h + "px";
    var context = canvas.getContext("2d");
    context.scale(2,2);

    html2canvas(document.getElementById("printDiv"), {
        async: false,
        canvas: canvas,
        allowTaint: true,
		// taintTest: false,
        onrendered: function() {
            var contentWidth = canvas.width;
            var contentHeight = canvas.height;

            //一页pdf显示html页面生成的canvas高度;
            var pageHeight = contentWidth / 592.28 * 841.89;
            //未生成pdf的html页面高度
            var leftHeight = contentHeight;
            //页面偏移
            var position = 0;
            //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            var imgWidth = 592.28;
            var imgHeight = 592.28/contentWidth * contentHeight;

            var pageData = canvas.toDataURL('image/jpeg',1);

            var pdf = new jsPDF('', 'pt', 'a4');

            //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
            //当内容未超过pdf一页显示的范围，无需分页
            if (leftHeight < pageHeight) {
                pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
            } else {
                while(leftHeight > 0) {
                    pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                    leftHeight -= pageHeight;
                    position -= 841.89;
                    //避免添加空白页
                    if(leftHeight > 0) {
                        pdf.addPage();
                    }
                }
            }

            pdf.save(fileName + '.pdf');
        }
    });




//    return html2canvas(document.getElementById("printDiv"), {
//         async: false,
//         allowTaint: true,
//         taintTest: false,
//         backgroundColor:"#FFF",
//         onrendered: function(canvas) {
//             var fileCode = null;
//             canvas.id = "mycanvas";
// //          document.body.appendChild(canvas);
//             //生成base64图片数据
//             var dataUrl = canvas.toDataURL();
//             // alert(dataUrl);
// 			/*
// 			 var newImg = document.createElement("img");
// 			 newImg.src =  dataUrl;
// 			 document.body.appendChild(newImg);*/
//
// 			/*
// 			 var image = canvas.toDataURL("image/png").replace("image/jpeg", "image/octet-stream");
// 			 window.location.href=image;*/
//             //image/png
// 			/* var image    = canvas.toDataURL("image/png");
// 			 var w=window.open('about:blank','image from canvas');
// 			 w.document.write("<img src='"+image+"' alt='from canvas'/>"); */
//
//             var pos = dataUrl.indexOf("4")+2;
//             dataUrl = dataUrl.substring(pos, dataUrl.length);//去掉Base64:开头的标识字符
//             $.ajax({
//                 type: "POST",
//                 url: getRealPath() + "/common/canvas2Img.do",
//                 async: false,
//                 xhrFields: { withCredentials: true },
//                 data: { 'base64StrImgData': dataUrl, "descs": descs},
//                 dataType: "json",
//                 success: function (data11) {
//                 	if (data11.status == 'SUCCESS') {
//                         fileCode = data11.data;
//                     } else {
//                 		fileCode = null;
// 					}
//                 },
//                 error: function (err) {
//                     fileCode = null;
//                 }
//             });
//             loadimg(fileCode);
//         }
//     });
	//化学品选择

}
function selectMater(openType) {
    layer.open({
        type: 2,
        title: '选择化学品',
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['300px', '440px'],
        content: [getRealPath() +'/sysman/materialInfo/materialInfoList.do?openNewPro=New&openType='+openType,'no']
    });
}

// formbody高度调整
function toAdapt(delH) {
    if(!isNaN(delH)){
        $(".formbody").css("min-height",$(window).height()-delH);
    }
}
//页面调整
function changeAdapt(height) {
    toAdapt(height);
    $(window).on("resize",function () {
        toAdapt(height);
    });
}

//公安查询 机关下的企业并选择
function selEnp() {
    layer.open({
        type : 2,
        title : "企业选择",
        shadeClose : true,
        shade : 0.7,
        maxmin : false,
        area : [ '800px', '500px' ],
        content : [getRealPath()+"/common/enpQuery/toQueryView.do",'no']
    });
}